<?php
/**
 * ProgramController is used for management of program.
 * 
 * LBB Solutions Oy 版权所有 © 2013
 */
class ProgramController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow authenticated user to perform below actions
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionIndex() {
		//fetch the program terms
		$sql_terms = 'SELECT caption, terms FROM tbl_merchant_program_terms WHERE id_merchant=:id_merchant ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_terms);
		$program = $command->queryRow(true, array(':id_merchant' => Yii::app()->user->id));
		$connection->active = false;
		
		$this->render('index', array('program'=>$program));
	}
	
	/**
	 * Only for AJAX request.
	 */
	public function actionList($type = null) {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		//get type=?
		$s_where = null;
		if ($type == 'select') {
			$s_where = ' AND status=1 ';
		}
		
		// this part is for AJAX request
		$sql_programs = 'SELECT id, id_merchant, title, description, required_points, status
			FROM tbl_merchant_program 
			WHERE id_merchant=:id_merchant AND trash=0 '
			. $s_where
			. ' ORDER BY required_points';
		
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_programs);
		$rows = $command->queryAll(true, array(':id_merchant' => Yii::app()->user->id));
		$connection->active = false;
		
		if ($type === 'select') {
			$this->renderPartial('_list_select', array('rows'=>$rows));
		} else {
			$this->renderPartial('_list', array('rows'=>$rows));
		}
	}
	
	/**
	 * Popup a browser window.
	 */
	public function actionPrint() {
		// this part is for AJAX request
		$sql_programs = 'SELECT id, id_merchant, title, description, required_points, status
			FROM tbl_merchant_program 
			WHERE id_merchant=:id_merchant AND trash=0 AND status=1
			ORDER BY required_points';
		$sql_terms = 'SELECT caption, terms FROM tbl_merchant_program_terms WHERE id_merchant=:id_merchant ';
		
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_programs);
		$rows = $command->queryAll(true, array(':id_merchant' => Yii::app()->user->id));
		$command = $connection->createCommand($sql_terms);
		$program = $command->queryRow(true, array(':id_merchant' => Yii::app()->user->id));
		$connection->active = false;
		
		$textChecking = $program;
		foreach ($rows as $i => $r) {
			$textChecking[$i] = $r['title'] . $r['description'];
		}
		$pdf_lang = 'en';
		if (count($textChecking) == 0) $pdf_lang = 'en';
		elseif (MerchantObject::IsChineseInProgramTerms($textChecking)) $pdf_lang = 'cn';
		else $pdf_lang = 'en';
		$_GET['lang'] = $pdf_lang;
		
		$this->layout = '//layouts/layout-print-pdf';
		$html2pdf = Yii::app()->ePdf->HTML2PDF();
		//$html2pdf->setDefaultFont('droidsansfallback');
        $html2pdf->WriteHTML($this->render('list_print', array('rows'=>$rows, 'program'=>$program, 'pdf_lang'=>$pdf_lang), true));
        $html2pdf->Output('program.pdf');
	}
	
	/**
	 * Preview a browser window.
	 */
	public function actionPreview() {
		// this part is for AJAX request
		$sql_programs = 'SELECT id, id_merchant, title, description, required_points, status
			FROM tbl_merchant_program 
			WHERE id_merchant=:id_merchant AND trash=0 AND status=1
			ORDER BY required_points';
		$sql_terms = 'SELECT caption, terms FROM tbl_merchant_program_terms WHERE id_merchant=:id_merchant ';
		
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_programs);
		$rows = $command->queryAll(true, array(':id_merchant' => Yii::app()->user->id));
		$command = $connection->createCommand($sql_terms);
		$program = $command->queryRow(true, array(':id_merchant' => Yii::app()->user->id));
		$connection->active = false;
		
		$this->layout = '//layouts/layout-print';
		$this->render('list_preview', array('rows'=>$rows, 'program'=>$program));
		Yii::app()->end();
	}
	
	/**
	 * Add a program. Only for AJAX request.
	 */
	public function actionAdd() {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$points = (int)Yii::app()->request->getPost('points');
		if ($points < 1) {
			throw new CHttpException(500, '{"name":"error", "message":"The points must be entered and cannot be 0!"}');
		}
		$title = trim(Yii::app()->request->getPost('title'));
		if (empty($title)) {
			throw new CHttpException(500, '{"name":"title", "message":"Please enter the program title!"}');
		}
		$desc = Yii::app()->request->getPost('desc');
		
		$params = array(
			':id_merchant' => Yii::app()->user->id,
			':title' => $title,
			':description' => $desc,
			':required_points' => $points,
			':status' => 0,//unpublished
		);
		$sql_insert = 'INSERT INTO tbl_merchant_program(id_merchant, title, description, required_points, status)
			VALUES (:id_merchant, :title, :description, :required_points, :status)';
		$sql_program = 'SELECT id, id_merchant, title, description, required_points, status
			FROM tbl_merchant_program WHERE id_merchant=:id_merchant 
			AND title=:title AND description=:description AND required_points=:required_points AND status=:status
			AND trash=0 AND UNIX_TIMESTAMP(create_time)>:create_time
			LIMIT 1';
		try {
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql_insert);
			$command->execute($params);
			
			$params[':create_time'] = time() - 5;
			$command = $connection->createCommand($sql_program);
			$row = $command->queryRow(true, $params);
			$connection->active = false;
		} catch (Exception $ex) {
			$connection->active = false;
			$message = $ex->getMessage() . "\n" . $ex->getTraceAsString();
			BUtils::TraceError($message);
			if (!YII_DEBUG) {
				$message = '{"name":"error", "message":"Fail to add this program due to too many users at the moment! Please try again in minutes."}';
			}
			throw new CHttpException(500, $message);
		}
		
		$this->renderPartial('_single', array('r'=>$row));
	}
	
	/**
	 * Publish a program. Only for AJAX request.
	 * @param type $id
	 */
	public function actionPublish($id) {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$sql_publish = 'UPDATE tbl_merchant_program SET status=1
			WHERE id=:id AND id_merchant=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_publish);
		$command->execute(array(
			':id' => $id,
			':id_merchant' => Yii::app()->user->id,
		));
		$connection->active = false;
	}
	
	/**
	 * Trash a program.
	 * @param type $id
	 */
	public function actionTrash($id) {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$sql_trash = 'UPDATE tbl_merchant_program SET trash=1
			WHERE id=:id AND id_merchant=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_trash);
		$command->execute(array(
			':id' => $id,
			':id_merchant' => Yii::app()->user->id,
		));
		$connection->active = false;
	}
	
	/**
	 * Save the terms.
	 * Post: terms=?
	 */
	public function actionTerms() {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$terms = strip_tags(trim(Yii::app()->request->getPost('terms')));
		
		$sql_select = 'SELECT id_merchant FROM tbl_merchant_program_terms WHERE id_merchant=:id_merchant';
		$params = array(':id_merchant' => (int)Yii::app()->user->id);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_select);
		$row = $command->queryRow(true, $params);
		if (empty($row['id_merchant'])) {
			$sql_insert = 'INSERT tbl_merchant_program_terms(id_merchant, terms) VALUES(:id_merchant, :terms)';
			$params[':terms'] = $terms;
			$command = $connection->createCommand($sql_insert);
			$command->execute($params);
		} else {
			$sql_update = 'UPDATE tbl_merchant_program_terms SET terms=:terms WHERE id_merchant=:id_merchant ';
			$params[':terms'] = $terms;
			$command = $connection->createCommand($sql_update);
			$command->execute($params);
		}
		$connection->active = false;
	}
	
	/**
	 * Save the caption.
	 * Post: caption=?
	 */
	public function actionCaption() {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$caption = strip_tags(trim(Yii::app()->request->getPost('caption')));
		
		$sql_select = 'SELECT id_merchant FROM tbl_merchant_program_terms WHERE id_merchant=:id_merchant';
		$params = array(':id_merchant' => (int)Yii::app()->user->id);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_select);
		$row = $command->queryRow(true, $params);
		if (empty($row['id_merchant'])) {
			$sql_insert = 'INSERT tbl_merchant_program_terms(id_merchant, caption) VALUES(:id_merchant, :caption)';
			$params[':caption'] = $caption;
			$command = $connection->createCommand($sql_insert);
			$command->execute($params);
		} else {
			$sql_update = 'UPDATE tbl_merchant_program_terms SET caption=:caption WHERE id_merchant=:id_merchant ';
			$params[':caption'] = $caption;
			$command = $connection->createCommand($sql_update);
			$command->execute($params);
		}
		$connection->active = false;
	}
}